from flask import current_app, request, render_template, session, jsonify
from flask import g

from info import constants
from info.models import User, News, Category
from info.modules.utils.common import user_login_data
from info.modules.utils.response_code import RET
from . import index_blu


# 访问根路径
@index_blu.route("/")
@user_login_data
def index():
    # None是以防万一,从哪获取的,redis数据库?不是,比较复杂???浏览器没有数据时,是无法找到的,
    # 有点明白了,在浏览器获取名字为session的cookie,以cookie为键获得redis数据库里的值result,
    #这个result是一个字典,user_id是key, id 是值2

    # 右侧新闻点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    range_news_list = []
    # 如果news_list是空,返回None,不报错=>news_list is not iterator
    for news in news_list if news_list else None:
        # news 是一个User的对象,即模板对象,自定义函数to_basic_dict()
        range_news_list.append(news.to_basic_dict())


    # 获取新闻分类数据, 未完成
    categories_list = []
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)


    for category in categories:
        categories_list.append(category.to_dict())



    # 组装数据
    data = {
        "user_info": g.user.to_dict() if g.user else None,
        "range_news_list": range_news_list,
        "categories_list": categories_list
    }

    return render_template("news/index.html", data=data)


# 访问favicon.ico图标
@index_blu.route("/favicon.ico")
def favicon():
    return current_app.send_static_file("news/favicon.ico")


# 访问首页新闻
@index_blu.route("/news_list")
def newsList():

    # 1. 获取数据cid, page, per_page
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    pre_page = request.args.get("per_page", constants.HOME_PAGE_MAX_NEWS)


    # 2. 验证数据
    try:
        cid = int(cid)
        page = int(page)
        pre_page = int(pre_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 查询数据
    try:
        if cid == 1 :
            paginate = News.query.order_by(News.create_time.desc()).paginate(page, pre_page, False)
        else:
            paginate = News.query.filter(News.category_id==cid).order_by(News.create_time.desc()).paginate(page, pre_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")


    # 4. 拼接数据
    news_list = paginate.items
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_basic_dict())
    data = {
        "cid": cid,
        "totalPage": paginate.pages,
        "currentPage": paginate.page,
        "newsList": news_dict_list
    }

    # 5. 返回响应
    return jsonify(errno=RET.OK, errmsg="OK", data=data)
